import pinia from '@/store';
import useUserStore from '@/store/user';
import progress from 'nprogress';
import 'nprogress/nprogress.css';
import { createRouter, createWebHistory, type RouteLocationNormalized } from 'vue-router';
import { constantRoute } from './routers';

progress.configure({ showSpinner: false })
const userStore = useUserStore(pinia)

const router = createRouter({
    history: createWebHistory(),
    routes: constantRoute,
    scrollBehavior() {
        return { left: 0, top: 0 }
    }

})

export default router

//进度条
router.beforeEach(() => {
    progress.start();
});
// 鉴权
router.beforeEach((to: RouteLocationNormalized) => {
    if (userStore.token) {//已登录
        if (to.path == "/login") {
            return { path: "/home" }
        }
        return;
    } else {//未登录
        if (to.path != "/login") {
            return { path: "/login", query: { redirect: to.fullPath } };
        }
        return;
    }
});

// 获得用户信息
router.beforeEach(async () => {
    if (!userStore.name) {
        await userStore.userInfo();
    }
});

router.afterEach(() => {
    progress.done();
});

